﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GPMS.Web.Controllers
{
    using GPMS.BLL;
    using GPMS.Model;
    public class RoleController : BaseController
    {

        public ActionResult List()
        {
            return PartialView(
                gpmsDb
                .Roles
                .Where(r => r.IsDeleted == false)
                .ToList()
                );
        }

        public ActionResult Permission(Guid id)
        {
            return PartialView(RoleHelper.GetPermission(id,gpmsDb));
        }
        [HttpPost]
        public ActionResult Permission(Guid id,FormCollection collection)
        {
            try
            {
            RoleHelper.SavePermission(id,collection, gpmsDb);
                return Success(null);
            }
            catch (Exception e)
            {
                return JsonError("更新失败:" + e.Message);
            }
        }

        public ActionResult Create()
        {
            return View(new Role());
        } 

        [HttpPost]
        public ActionResult Create(Role role)
        {
            if (ModelState.IsValid)
            {
                RoleHelper.Add(role, gpmsDb);
                return Success(null);
            }
            return JsonError(GetError(ModelState));
        }
        
        public ActionResult Edit(Guid id)
        {
            return View(RoleHelper.Get(id, gpmsDb));
        }

        [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            var role = RoleHelper.Get(id, gpmsDb);
            try
            {
                UpdateModel(role, collection);
                gpmsDb.SaveChanges();
                return Success(null);
            }
            catch(Exception ex)
            {
                return JsonError("更新失败:" + ex.Message);
            }
        }

 
        public ActionResult Delete(Guid id)
        {
            return Confirm(string.Format("确定删除角色：{0} ?",
                RoleHelper.Get(id, gpmsDb).RoleName));
        }



        [HttpPost]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            try
            {
                RoleHelper.Delete(id, gpmsDb);
                return Success(null);
            }
            catch(Exception ex)
            {
                return JsonError("更新失败:" + ex.Message);
            }
        }
    }
}
